<template>
<div>
  <el-form size="mini" ref="form" :model="admin" :rules="formRules" label-width="120px" status-icon>
    <el-form-item label="账号" prop="account.account">
      <el-input
        v-model.trim="admin.account.account"
        placeholder="请输入管理员账号"
        :disabled="id !== undefined && id.length > 0"
        maxlength="20"
        show-word-limit
      ></el-input>
    </el-form-item>
    <el-form-item label="名称" prop="nickname">
      <el-input v-model.trim="admin.nickname" placeholder="请输入管理员名称" maxlength="10" show-word-limit></el-input>
    </el-form-item>
    <el-form-item v-if="!id" label="密码" prop="account.password">
      <el-input
        type="password"
        placeholder="请输入管理员密码"
        v-model.trim="admin.account.password"
        auto-complete="new-password"
        minlength="6"
        show-word-limit
        maxlength="20"
      ></el-input>
    </el-form-item>
    <el-form-item label="状态" prop="account.status">
      <el-select
        style="width: 150px"
        class="filter-item"
        placeholder="状态"
        v-model="admin.account.status"
      >
        <el-option
          v-for="item in stateOptions"
          :key="item.name"
          :label="item.name"
          :value="item.value"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="角色">
      <el-button type="text" @click="handleSelectRoles">添加角色</el-button>
      <el-table
        ref="dataTable"
        stripe
        border
        fit
        size="mini"
        highlight-current-row
        :data="admin.roles"
        style="width: 100%"
      >
        <el-table-column prop="name" label="名称" width="180"></el-table-column>
        <el-table-column prop="desc" label="描述"></el-table-column>
        <el-table-column align="center" width="50">
          <template slot-scope="scope">
            <i
              class="el-icon-delete"
              style="cursor:pointer;"
              alt="移除角色"
              @click="handleRemoveRole(scope.row)"
            ></i>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button v-if="id" type="primary" @click="onSubmit(true)" v-waves>保存</el-button>
      <el-button v-if="!id" type="primary" @click="onSubmit(true)" v-waves>保存并继续</el-button>
      <el-button v-if="!id" type="primary" @click="onSubmit(false)" v-waves>保存并退出</el-button>
      <el-button v-waves @click="onCancel">取消</el-button>
    </el-form-item>
  </el-form>
   <filter-dialog
        ref="rolesTable"
        title="选择角色"
        :show.sync="selecteRoles.show"
        :rows="selecteRoles.rows"
        :total="selecteRoles.total"
        :index-column="true"
        :multiple-selected="true"
        width="80%"
        @page-info-change="handleRolePageInfoChange"
        :show-loading="selecteRoles.showLoading"
        @close="handleRolesDialogClose"
        @selected="handleRolesSelected"
      >
        <template slot="condition">
          <el-form-item>
            <el-input
              @keyup.enter.native="handleRolesFilter"
              placeholder="角色名称"
              v-model.trim="selecteRoles.condition.keyword"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              class="filter-item"
              style="margin-left: 10px;"
              type="primary"
              v-waves
              icon="el-icon-search"
              @click="handleRolesFilter"
            >搜索</el-button>
          </el-form-item>
        </template>
        <template>
          <el-table-column
            min-width="150px"
            label="名称"
            align="center"
            sortable="custom"
            property="name"
          >
            <template slot-scope="scope">
              <span>{{scope.row.name}}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="150px" label="描述" align="left" header-align="center">
            <template slot-scope="scope">
              <span>{{scope.row.desc}}</span>
            </template>
          </el-table-column>
        </template>
      </filter-dialog>
  </div>
</template>

<style scoped>
.el-form {
  margin: 20px;
}
</style>

<script>
import adminInfoApi from '@/api/admin/adminUserInfo'
import adminFormApi from '@/api/admin/adminUserForm'
import waves from '@/directive/waves' // 水波纹指令
// import _ from 'underscore'
import FilterDialog from '@/components/filterDialog/filterDialog'

export default {
  directives: {
    waves
  },
  props: ['id'],
  data () {
    return {
      admin: {
        id: 0,
        account: {
          account: null,
          password: null,
          status: 1
        },
        nickname: null,
        roles: []
      },
      stateOptions: [
        {
          name: '启用',
          value: 1
        },
        {
          name: '禁用',
          value: 0
        }
      ],
      formRules: {
        'account.account': [
          {
            required: true,
            message: '请输入管理员账号'
          },
          {
            min: 6,
            max: 20,
            message: '账号长度需在6到20个字符之间'
          },
          {
            validator: (rule, value, callback) => {
              if (this.id) {
                return callback()
              }
              adminFormApi.checkAccount(value).then(res => {
                if (!res.data) {
                  return callback(new Error('账号已存在，请重新输入'))
                }
                return callback()
              })
            },
            trigger: 'blur'
          }
        ],
        nickname: [
          {
            required: true,
            message: '请输入管理员名称'
          },
          {
            max: 10,
            message: '管理员名称长度不能超过 10 个字符'
          }
        ],
        'account.password': [
          {
            required: true,
            message: '请输入管理员密码'
          },
          {
            min: 6,
            max: 20,
            message: '密码长度在 6 到 20 个字符'
          }
        ]
      },
      selecteRoles: {
        show: false,
        showLoading: false,
        rows: [],
        total: 0,
        condition: {
          keyword: undefined
        }
      }
    }
  },
  watch: {
    id () {
      this.resetForm()
    }
  },
  components: {
    FilterDialog
  },
  methods: {
    /**
     * 提交数据
     * @param {*} goon 新增后是否继续新增
     */
    onSubmit (goon) {
      this.$refs.form.validate().then(response => {
        if (!response) {
          return
        }
        if (this.admin.roles && this.admin.roles.length > 0) {
          this.admin.roleIds = this.admin.roles.map(role => {
            return role.id
          })
        }
        this.admin.enabled = this.state === 1 ? 'Yes' : 'No'
        this.admin.state = this.state
        if (!this.id) {
          adminFormApi.insert(this.admin).then(response => {
            this.$notify({
              title: '成功',
              message: '管理员创建成功',
              type: 'success'
            })
            if (goon) {
              this.resetForm()
            } else {
              this.$router.replaceBy(this.$router.routesConfig.adminList)
            }
          })
        } else {
          adminInfoApi.update(this.admin).then(response => {
            this.$notify({
              title: '成功',
              message: '管理员更新成功',
              type: 'success'
            })
            this.$router.replaceBy(this.$router.routesConfig.adminList)
          })
        }
      })
    },
    /**
     * 取消按钮处理
     */
    onCancel () {
      this.$router.replaceBy(this.$router.routesConfig.adminList)
    },
    /**
     * 加载角色数据
     * @param {*} pageInfo 分页信息
     */
    getRoleList (pageInfo) {
      this.selecteRoles.showLoading = true
      if (this.id) {
        adminInfoApi.getRolePaged({
          pageInfo,
          condition: this.selecteRoles.condition
        })
          .then(response => {
            this.selecteRoles.rows = response.data.content
            this.selecteRoles.total = response.data.totalElements
            this.selecteRoles.showLoading = false
          })
          .catch(response => {
            this.selecteRoles.showLoading = false
          })
      } else {
        adminFormApi.getRolePaged({
          pageInfo,
          condition: this.selecteRoles.condition
        })
          .then(response => {
            this.selecteRoles.rows = response.data.content
            this.selecteRoles.total = response.data.totalElements
            this.selecteRoles.showLoading = false
          })
          .catch(response => {
            this.selecteRoles.showLoading = false
          })
      }
    },
    /**
     * 获取管理员信息
     */
    getAdmin () {
      if (this.id) {
        adminInfoApi.getById(this.id).then(response => {
          this.admin = response.data
          // this.admin.state = response.data.enabled === 'Yes' ? 1 : 0
          // this.state = this.admin.state
        })
      }
    },
    /**
     * 重置表单
     */
    resetForm () {
      this.$refs.form.resetFields()
      this.admin.id = ''
      this.admin.roles = []
      this.selecteRoles.rows = []
      this.selecteRoles.total = 0
      this.selecteRoles.condition.name = undefined
    },
    /**
     * 选择角色
     */
    handleSelectRoles () {
      this.selecteRoles.show = true
    },
    /**
     * 移除角色
     */
    handleRemoveRole (role) {
      this.admin.roles = this.admin.roles.filter(ar => {
        return !(ar.id === role.id)
      })
    },
    /**
     * 过滤角色
     */
    handleRolesFilter () {
      this.$refs.rolesTable.changeCondition()
    },
    /**
     * 角色选择
     */
    handleRolesSelected (roles) {
      roles.forEach(r => {
        if (
          !this.admin.roles.find(ar => {
            return ar.id === r.id
          })
        ) {
          this.admin.roles.push(r)
        }
      })
    },
    /**
     * 选择角色窗口关闭
     */
    handleRolesDialogClose () {
      this.selecteRoles.condition.name = undefined
      this.selecteRoles.rows = []
    },
    /**
     * 查询角色条件变更
     */
    handleRolePageInfoChange (pageInfo) {
      this.getRoleList(pageInfo)
    }
  },
  created () {
    this.getAdmin()
  }
}
</script>
